package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.IGStoreLvAdapter;
import com.example.administrator.yanfoxconn.bean.BodyONE;
import com.example.administrator.yanfoxconn.bean.ExcePhoto;
import com.example.administrator.yanfoxconn.bean.IGMessage;
import com.example.administrator.yanfoxconn.bean.JVSchoolInfo;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.TimeDateUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.TouchImageView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用途：宿舍物品放行KA
 *      門崗放行KD
 * Created by Song on 2021.
 */
public class KAMainActivity extends BaseActivity implements View.OnClickListener{
    private final int MESSAGE_SET_TEXT = 1;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_UP = 3;//提交信息
    private final int MESSAGE_JUMP = 4;//跳轉維護界面
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤
    private final int MESSAGE_SET_CHECK = 6;
    private final int MESSAGE_SET_DOOR=8;//門崗
//    private final int

    private List<ExcePhoto> photos;
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題


    @BindView(R.id.tr_dorm_date)
    TableRow trDormDate;//宿舍放行時間行
    @BindView(R.id.tv_dorm_date)
    TextView tvDormDate;//宿舍放行時間
    @BindView(R.id.tv_status)
    TextView tvStatus;//狀態
    @BindView(R.id.tv_id)
    TextView tvId;//工號
    @BindView(R.id.tv_name)
    TextView tvName;//姓名
    @BindView(R.id.tv_dep)
    TextView tvDep;//部門
    @BindView(R.id.tv_room)
    TextView tvRoom;//住宿信息
    @BindView(R.id.tv_phone)
    TextView tvPhone;//手機號
    @BindView(R.id.tv_leave_reason)
    TextView tvReason;//放行原因
    @BindView(R.id.tv_leave_date)
    TextView tvDate;//放行日期
    @BindView(R.id.tr_real_people)
    TableRow trRealPeople;//證明人行
    @BindView(R.id.tv_real_people)
    TextView tvRealPeople;//證明人
    @BindView(R.id.tr_real_door)
    TableRow trRealDoor;//放行門崗
    @BindView(R.id.sp_real_door)
    Spinner spRealDoor;//放行門崗
    @BindView(R.id.lv_store)
    RecyclerView lvStore;//帶儲位物品排配列表
    @BindView(R.id.ll_get_image)
    LinearLayout llGetImage;//異常圖片

    @BindView(R.id.btn_leave)
    Button btnLeave;//放行
    @BindView(R.id.btn_back)
    Button btnBack1;//返回

    private IGStoreLvAdapter storeLvAdapter;
    private List<IGMessage> msg, storeList,doorList;
    private List<BodyONE> bodyOne;
    private String r_id,flag,date,from,door="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ka_leave);
        ButterKnife.bind(this);

        tvTitle.setText("物品放行");
        btnBack.setOnClickListener(this);
        btnBack1.setOnClickListener(this);
        btnLeave.setOnClickListener(this);
        r_id=getIntent().getStringExtra("r_id");
        from = getIntent().getStringExtra("from");
        LinearLayoutManager layoutManager = new LinearLayoutManager(KAMainActivity.this);
        lvStore.setLayoutManager(layoutManager);
        lvStore.setItemViewCacheSize(500);

        getInfo();
    }
    //查看員工信息
    private void getInfo() {

        showDialog();
        final String url = Constants.HTTP_DORM_RELEASE_DETAIL + "?r_id=" + r_id;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForGet(url);
                Log.e("---------", "result==fff===" + result);
                dismissDialog();
                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                if (result != null) {
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        Log.e("--fff---------", "result==" + result);
                        JsonObject array = jsonObject.get("data").getAsJsonObject();
                        msg = new ArrayList<IGMessage>();
                        bodyOne = new ArrayList<BodyONE>();
                        JsonArray bodyArray = array.get("body").getAsJsonArray();
                        for (JsonElement type : bodyArray) {
                            BodyONE humi = gson.fromJson(type, BodyONE.class);
                            bodyOne.add(humi);
                        }

                        Message message = new Message();
                        message.what = MESSAGE_SET_TEXT;
                        message.obj = array;
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                }
            }
        }.start();
    }

//    提交前檢查
    private void check() {
        String nameE = "",doorE = "";

        try {
            nameE = URLEncoder.encode(URLEncoder.encode(FoxContext.getInstance().getName(), "UTF-8"), "UTF-8");
            doorE= URLEncoder.encode(URLEncoder.encode(door, "UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String url = Constants.HTTP_DORM_RELEASE_SAFE_OK+"?r_id=" + r_id+"&creator="+nameE+"&flag="+flag+"&door="+doorE; //此處寫上自己的URL
            //開啟一個新執行緒，向伺服器上傳資料
        Log.e("-----------", "url==" + url);
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                            Log.e("---------", "result==fff===" + result);
                            JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                            String errCode = jsonObject.get("errCode").getAsString();
                            if (errCode.equals("200")) {
                                Message message = new Message();
                                message.what = MESSAGE_TOAST;
                                message.obj = jsonObject.get("errMessage").getAsString();
                                mHandler.sendMessage(message);

                            } else{
                                Log.e("-----------", "result==" + result);
                                Message message = new Message();
                                message.what = MESSAGE_TOAST;
                                message.obj = jsonObject.get("errMessage").getAsString();
                                mHandler.sendMessage(message);
                            }
                        }else{
                            Message message = new Message();
                            message.what = MESSAGE_NETMISTAKE;
                            mHandler.sendMessage(message);
                            finish();
                        }
                }
            }.start();
        }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MESSAGE_TOAST://Toast彈出
//                    aboutAlert(msg.obj.toString(),MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
                    finish();
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(KAMainActivity.this,R.string.net_mistake);
                    break;
                case MESSAGE_SET_TEXT://text賦值
                    JsonObject mes = (JsonObject) msg.obj;
                    tvStatus.setText(mes.get("R_STATUS").getAsString());
                    tvId.setText(mes.get("R_NO").getAsString());
                    tvName.setText(mes.get("R_NAME").getAsString());
                    tvDep.setText(mes.get("R_DEP").getAsString());
                    tvRoom.setText(mes.get("R_AREA").getAsString()+mes.get("R_BUILDING").getAsString()+mes.get("R_FLOOR").getAsString()+mes.get("R_ROOM").getAsString()+mes.get("R_BED").getAsString());
                    tvPhone.setText(mes.get("R_TEL").getAsString());
                    tvReason.setText(mes.get("R_REASON").getAsString());
                    tvDate.setText(mes.get("R_RELEASE_DATE").getAsString());
                    if (mes.get("R_STATUS").getAsString().equals("已放行")){
                        btnLeave.setVisibility(View.GONE);
                        btnBack1.setVisibility(View.GONE);
                    }
                    if (mes.get("R_DORM_RELEASE_DATE").getAsString().equals("")){
                        flag="Dorm";
                        trDormDate.setVisibility(View.GONE);
                        tvStatus.setBackgroundColor(getResources().getColor(R.color.color_00CCFF));
                    }else {

                        flag="Safe";
                        trDormDate.setVisibility(View.VISIBLE);
                        date=mes.get("R_DORM_RELEASE_DATE").getAsString();

                        tvDormDate.setText(mes.get("R_DORM_RELEASE_DATE").getAsString());
                        tvStatus.setBackgroundColor(getResources().getColor(R.color.color_f5a306));
                        Date d  = new Date(date);
                        if (TimeDateUtils.dateDiff(d, TimeDateUtils.getNowDate())>120){
                            tvStatus.setBackgroundColor(getResources().getColor(R.color.color_ff552e));
                            tvStatus.setText("超時不予放行！");
                        }
                        if (from.equals("kd")){
                        trRealDoor.setVisibility(View.VISIBLE);
                        getDoor();}
                    }
                    if (mes.get("R_PROVE_NO").getAsString().equals("")) {
                        trRealPeople.setVisibility(View.GONE);
                        llGetImage.setVisibility(View.GONE);
                    }else{
                        tvRealPeople.setText(mes.get("R_PROVE_NO").getAsString() + mes.get("R_PROVE_NAME").getAsString());

                        TouchImageView imageView = new TouchImageView(KAMainActivity.this);
//                        ImageView imageView = new ImageView(ZhiyinshuiExceDetailActivity.this);
                        String imgStr = mes.get("R_PROVE_SIGN").getAsString();
                        Log.e("------imgStr-----", "======"+imgStr);
                        byte[] decode = Base64.decode(imgStr, Base64.DEFAULT);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
                        imageView.setImageBitmap(bitmap);
                        //設置點擊放大事件
                        imageView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                int[] location = new int[2];
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    Rect frame = new Rect();
                                    getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                                    int statusBarHeight = frame.top;

                                    view.getLocationOnScreen(location);
                                    location[1] += 0;
                                } else {
                                    view.getLocationOnScreen(location);
                                }
                                view.invalidate();
                                int width = view.getWidth();
                                int height = view.getHeight();

                                Intent intent = new Intent(KAMainActivity.this, BigImageActivity.class);
                                Bundle b = new Bundle();
                                b.putString(BigImageActivity.QR_IMAGE_URL, imgStr);
                                intent.putExtras(b);
//                                intent.putExtra(BigImageActivity.PHOTO_SELECT_POSITION,);
                                intent.putExtra(BigImageActivity.PHOTO_SELECT_X_TAG, location[0]);
                                intent.putExtra(BigImageActivity.PHOTO_SELECT_Y_TAG, location[1]);
                                intent.putExtra(BigImageActivity.PHOTO_SELECT_W_TAG, width);
                                intent.putExtra(BigImageActivity.PHOTO_SELECT_H_TAG, height);
                                startActivity(intent);
                                overridePendingTransition(0, 0);
                            }
                        });
                        llGetImage.addView(imageView);
                    }

                        storeLvAdapter = new IGStoreLvAdapter(KAMainActivity.this, bodyOne, "ka");
                    lvStore.setAdapter(storeLvAdapter);
                    break;
                case MESSAGE_UP://提交響應
                    worningAlert(msg.obj.toString(),MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
                    break;
                case MESSAGE_JUMP://跳轉維護異常界面
                    worningAlert(msg.obj.toString(),MESSAGE_JUMP);
                    break;
                case MESSAGE_SET_DOOR://跳轉維護異常界面
                   setDoor();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void worningAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==MESSAGE_TOAST){
                            finish();
                        }else if (type==MESSAGE_JUMP){

                        }else if (type==MESSAGE_SET_CHECK){
                            check();
                        }
                    }
                })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_leave:

               if (flag.equals("Dorm")){
                   if (from.equals("ka")){
                       worningAlert("確認放行",MESSAGE_SET_CHECK);
                   }else{
                       ToastUtils.showLong(KAMainActivity.this,"請至宿服辦確認放行！");
                   }
                }else{
                   if (from.equals("kd")){
                    Date d  = new Date(date);
                    if (TimeDateUtils.dateDiff(d, TimeDateUtils.getNowDate())<120){
                    worningAlert("確認放行",MESSAGE_SET_CHECK);
                    }else{
                        ToastUtils.showShort(KAMainActivity.this,"超時不予放行！");
                    }
                   }else{
                       ToastUtils.showLong(KAMainActivity.this,"請至門崗確認放行！");
                   }
                }
                break;
        }
    }

    //門崗基本信息下拉
    private void getDoor(){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_DORM_RELEASE_DOOR ;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        doorList = new ArrayList<IGMessage>();

                        for (JsonElement type : array) {
                            IGMessage humi = gson.fromJson(type, IGMessage.class);
                            doorList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_DOOR;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setDoor(){
        List<String> doorName=new ArrayList<>();
        for (int i = 0;i<doorList.size();i++){
            doorName.add(doorList.get(i).getDoor());
        }
        //稽核課隊下拉列表選擇
        spRealDoor.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, doorName));
        spRealDoor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                door=doorName.get(position);
//            paramMap.put("kedui",str);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
}
